<!--
 * @Description: 邀请pk赛活动管理新增编辑页面
 * @Author: liyujie
 * @Date: 2021/10/20
 * @Last Modified by: liyujie
 * @Last Modified time: 2021/010/20
-->
<template>
    <div class="wrapper">
        <div class="content-wrapper">
            <!-- header -->
            <page-header :title="type === 'edit' ? '编辑活动' : type === 'add' ? '创建活动' : '查看活动'">
                <template slot="header-right">
                    <div
                        class="back"
                        @click="handleRoute('invitePkActivityList')"
                    >返回</div>
                </template>
            </page-header>
            <div>
                <div class="form-view">
                    <!--表单-->
                    <el-form
                        :model="ruleForm"
                        :rules="rules"
                        label-position="right"
                        ref="ruleForm"
                        label-width="192px"
                        class="form-wrap"
                        :disabled="type === 'detail'"
                        @submit.native.prevent
                    >
                        <div
                            class="form-title"
                            style="margin-top: 0"
                        >基本信息</div>
                        <el-form-item label="拉新类型">
                            <el-input
                                :value="`${ruleForm.task_category === 104 ? '个人邀请PK赛' : '学校邀请PK赛'}`"
                                size="medium"
                                style="width: 223px"
                                disabled
                            />
                        </el-form-item>
                        <el-form-item
                            label="活动期数"
                            prop="activity_index"
                            class="is-required"
                        >
                            <span style="color: #606266;margin-right: 6px">第</span>
                            <el-input-number
                                v-model="ruleForm.activity_index"
                                placeholder="请输入活动期数"
                                :step="1"
                                step-strictly
                                :controls="false"
                                :min="0"
                                size="medium"
                                style="width: 223px"
                                :disabled="type === 'detail' || isDisabled"
                            />
                            <span style="color: #606266;margin: 0 6px">期</span>
                        </el-form-item>
                        <el-form-item
                            label="活动时间"
                            prop="start_time"
                            class="is-required"
                        >
                            <div style="display: flex; align-items: center">
                                <el-form-item prop="start_time">
                                    <el-date-picker
                                        v-model="ruleForm.start_time"
                                        type="datetime"
                                        default-time="00:00:00"
                                        size="medium"
                                        placeholder="请选择开始时间"
                                        style="width: 218px"
                                        value-format="timestamp"
                                        :disabled="isDisabled"
                                    />
                                </el-form-item>
                                <span style="margin: 0 12px">-</span>
                                <el-form-item prop="end_time">
                                    <el-date-picker
                                        v-model="ruleForm.end_time"
                                        type="datetime"
                                        placeholder="请选择结束时间"
                                        default-time="23:59:59"
                                        size="medium"
                                        style="width: 218px"
                                        value-format="timestamp"
                                    />
                                </el-form-item>
                            </div>
                        </el-form-item>
                        <el-form-item
                            label="活动logo"
                            prop="task_logo_images"
                            class="is-required image-label"
                        >
                            <div class="upload-list">
                                <el-form-item
                                    v-for="(item, index) in ruleForm.task_logo_images"
                                    :key="index"
                                    class="upload-item"
                                    :prop="`task_logo_images[${index}].image`"
                                    :rules="rules.task_logo_images"
                                >
                                    <image-upload
                                        v-model="item.image"
                                        :limit="100"
                                        tips=""
                                        :type="isDisabled ? 'detail' : 'add'"
                                        class="task-logo-wrapper"
                                    />
                                    <div class="upload-text">{{ index + 1 }}个的样式</div>
                                </el-form-item>
                                <el-button
                                    type="text"
                                    size="medium"
                                    @click="$refs.imageSizeDemo.show()"
                                >
                                    查看示例
                                </el-button>
                            </div>
                        </el-form-item>
                        <div class="form-title">邀请奖励设置</div>
                        <el-form-item
                            label="邀请奖励APP显示金额"
                            prop="show_task_price"
                            class="is-required"
                        >
                            <el-input
                                v-model="ruleForm.show_task_price"
                                placeholder="请输入邀请奖励APP显示金额"
                                size="medium"
                                clearable
                                style="width: 360px"
                                :disabled="isDisabled"
                            >
                                <span
                                    slot="suffix"
                                    style="margin-right: 6px"
                                >元</span>
                            </el-input>
                        </el-form-item>
                        <el-form-item
                            label="精英等级"
                            class="is-required"
                        >
                            <el-select
                                v-model="ruleForm.student_limit_stuagent_level"
                                placeholder="全部精英"
                                size="medium"
                                style="width: 360px"
                            >
                                <el-option
                                    v-for="item in 5"
                                    :key="item"
                                    :label="`E${item - 1}以上（含E${item - 1}）`"
                                    :value="item - 1"
                                />
                                <el-option
                                    label="E5"
                                    :value="5"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item
                            label="APP显示状态"
                            class="is-required"
                            style="margin-bottom: 12px"
                        >
                            <el-radio-group
                                v-model="ruleForm.show_flag"
                                size="medium"
                            >
                                <el-radio :label="1">显示</el-radio>
                                <el-radio :label="0">隐藏</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item
                            label="学校限制"
                            class="is-required"
                        >
                            <el-radio-group
                                v-model="ruleForm.school_limit_type"
                                :disabled="isDisabled"
                            >
                                <el-radio :label="0">不限制</el-radio>
                                <el-radio :label="1">全部限制</el-radio>
                                <el-radio :label="2">部分学校</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item v-if="ruleForm.school_limit_type === 2">
                            <div class="school-wrapper">
                                <div class="school-header">已选学校</div>
                                <div
                                    class="school-content"
                                    v-if="ruleForm.binding_school_ids.length"
                                >
                                    <div class="btn-view">
                                        <div>已选学校<span class="count">（{{ ruleForm.binding_school_ids.length }}）</span></div>
                                        <el-button
                                            type="primary"
                                            size="medium"
                                            @click="handleSelectSchool('edit')"
                                        >
                                            修改已选学校
                                        </el-button>
                                    </div>
                                    <div class="table-wrapper">
                                        <el-table
                                            :data="pageData"
                                            ref="table"
                                            row-key="id"
                                            @selection-change="handleSelectedChange"
                                        >
                                            <el-table-column
                                                type="selection"
                                                width="50"
                                                reserve-selection
                                                align="center"
                                            />
                                            <el-table-column
                                                prop="school_name"
                                                label="学校名称"
                                            />
                                            <el-table-column
                                                prop="school_name"
                                                label="所在省市"
                                            >
                                                <template slot-scope="scope">
                                                    {{ scope.row.province_name }} - {{ scope.row.city_name }}
                                                </template>
                                            </el-table-column>
                                            <el-table-column
                                                label="操作"
                                                align="center"
                                            >
                                                <template slot-scope="scope">
                                                    <el-button
                                                        type="text"
                                                        :disabled="isDisabled"
                                                        @click="handleRemove(scope.row)"
                                                    >
                                                        移除
                                                    </el-button>
                                                </template>
                                            </el-table-column>
                                        </el-table>
                                    </div>
                                    <div class="table-footer">
                                        <div>
                                            <el-checkbox
                                                label=""
                                                v-model="checkAllStatus"
                                                :indeterminate="checkIndeterminate"
                                                :disabled="ruleForm.binding_school_ids.length === 0 || isDisabled"
                                                @change="handleSelectedAll"
                                            />
                                            <el-button
                                                size="small"
                                                type="text"
                                                style="margin-left: 12px"
                                                :disabled="multipleSelection.length === 0 || isDisabled"
                                                @click="handleRemoveBatch"
                                            >
                                                批量移除
                                            </el-button>
                                        </div>
                                        <div class="pagination">
                                            <el-pagination
                                                layout="prev, pager, next"
                                                :current-page.sync="page.now_page"
                                                :total="page.total_count"
                                                :page-size="page.page_size"
                                                @current-change="getPageData"
                                            />
                                        </div>
                                    </div>
                                </div>
                                <div
                                    class="school-content-empty"
                                    v-else
                                >
                                    <div class="empty-title">当前没有选择学校哦～</div>
                                    <div class="empty-sub-title">请点击下方按钮，选择部分可以参加活动的学校～</div>
                                    <div
                                        class="empty-btn"
                                        @click="handleSelectSchool"
                                    >选择学校</div>
                                </div>
                            </div>
                        </el-form-item>
                        <div class="form-title">
                            奖金池设置
                            <span class="form-tips">仅用于APP中显示</span>
                        </div>
                        <el-form-item label="指定排名奖励">
                            <div class="rank-wrapper">
                                <div
                                    class="rank-list"
                                    v-if="ruleForm.rank_award.length"
                                >
                                    <div
                                        class="rank-item"
                                        v-for="(item,index) in ruleForm.rank_award"
                                        :key="index"
                                    >
                                        <div class="rank-item__header">
                                            <div class="rank-num">第{{ numberChinese(index + 1) }}名</div>
                                            <el-button
                                                type="text"
                                                size="medium"
                                                :disabled="isDisabled"
                                                @click="ruleForm.rank_award.splice(index, 1)"
                                            >删除</el-button>
                                        </div>
                                        <div class="rank-item__content">
                                            <el-form-item
                                                :prop="`rank_award[${index}].award_money`"
                                                :rules="rules.award_money"
                                            >
                                                <el-input
                                                    v-model="item.award_money"
                                                    size="medium"
                                                    style="width: 100%"
                                                    placeholder="请输入"
                                                    :disabled="isDisabled"
                                                >
                                                    <span
                                                        slot="suffix"
                                                        style="margin-right: 6px"
                                                    >元</span>
                                                </el-input>
                                            </el-form-item>
                                        </div>
                                    </div>
                                </div>
                                <div
                                    class="empty-text"
                                    v-else
                                >在瓜分奖金池的基础上，额外的奖励...</div>
                                <el-button
                                    size="medium"
                                    icon="el-icon-plus"
                                    class="add-button"
                                    :disabled="isDisabled"
                                    v-if="ruleForm.rank_award.length < 10"
                                    @click="handleAddAward"
                                >新增</el-button>
                            </div>
                        </el-form-item>
                        <el-form-item
                            label="奖金池金额设置"
                            class="is-required"
                            v-if="ruleForm.task_category === 104"
                        >
                            <div class="award-wrapper">
                                <div class="award-item">
                                    <span>· 奖金池基础金额</span>
                                    <el-form-item prop="pool_award_pool_start_money">
                                        <el-input
                                            v-model="ruleForm.pool_award_pool_start_money"
                                            size="medium"
                                            placeholder="请输入"
                                            style="width: 206px;margin-right: 36px"
                                            :disabled="isDisabled"
                                        >
                                            <span
                                                slot="suffix"
                                                style="margin-right: 6px"
                                            >元</span>
                                        </el-input>
                                    </el-form-item>
                                    <span>奖金池上限</span>
                                    <el-form-item prop="pool_award_pool_max_money">
                                        <el-input
                                            v-model="ruleForm.pool_award_pool_max_money"
                                            size="medium"
                                            placeholder="请输入"
                                            style="width: 206px"
                                            :disabled="isDisabled"
                                        >
                                            <span
                                                slot="suffix"
                                                style="margin-right: 6px"
                                            >元</span>
                                        </el-input>
                                    </el-form-item>
                                </div>
                                <div class="award-item">
                                    <span>· 认证人数每增加</span>
                                    <el-form-item prop="pool_award_pool_step_require_student_count">
                                        <el-input
                                            v-model="ruleForm.pool_award_pool_step_require_student_count"
                                            size="medium"
                                            placeholder="请输入"
                                            style="width: 206px;margin-right: 36px"
                                            :disabled="isDisabled"
                                        >
                                            <span
                                                slot="suffix"
                                                style="margin-right: 6px"
                                            >人</span>
                                        </el-input>
                                    </el-form-item>
                                    <span>奖金池增加</span>
                                    <el-form-item prop="pool_award_pool_step_append_money">
                                        <el-input
                                            v-model="ruleForm.pool_award_pool_step_append_money"
                                            size="medium"
                                            placeholder="请输入"
                                            style="width: 206px"
                                            :disabled="isDisabled"
                                        >
                                            <span
                                                slot="suffix"
                                                style="margin-right: 6px"
                                            >元</span>
                                        </el-input>
                                    </el-form-item>
                                    <span class="form-tips">
                                        （以账号维度去统计，去重）
                                    </span>
                                </div>
                            </div>
                        </el-form-item>
                        <el-form-item
                            label="奖金池设置"
                            class="is-required"
                            v-if="ruleForm.task_category === 105"
                        >
                            <el-input-number
                                v-model="ruleForm.pool_award_money"
                                placeholder="请输入奖金池金额"
                                size="medium"
                                clearable
                                style="width: 469px"
                                :controls="false"
                                :step="0.01"
                                step-strictly
                                :min="0"
                            />
                        </el-form-item>
                        <el-form-item
                            label="瓜分奖金池设置"
                            class="is-required"
                        >
                            <div
                                class="award-wrapper"
                                style="padding: 32px 24px"
                            >
                                <div
                                    class="award-item"
                                    v-for="(item,index) in ruleForm.pool_award_pool_step_set"
                                    :key="index"
                                >
                                    <template v-if="index === 0">
                                        <span>· 总金额1</span>
                                        <el-form-item>
                                            <el-input
                                                v-model="item.award_money_percent"
                                                size="medium"
                                                placeholder="请输入"
                                                style="width: 206px;margin-right: 36px"
                                                :disabled="isDisabled"
                                            >
                                                <span
                                                    slot="suffix"
                                                    style="margin-right: 6px"
                                                >%</span>
                                            </el-input>
                                        </el-form-item>
                                        <span style="margin-left: -24px">所有参与用户参与瓜分</span>
                                    </template>
                                    <template v-else>
                                        <span>· 总金额{{ index + 1 }}</span>
                                        <el-form-item
                                            :prop="`pool_award_pool_step_set[${index}].rank_end_percent`"
                                            :rules="rules.rank_end_percent"
                                        >
                                            <el-input
                                                v-model="item.rank_end_percent"
                                                size="medium"
                                                placeholder="请输入"
                                                style="width: 206px;margin-right: 10px"
                                                :disabled="isDisabled"
                                            >
                                                <span
                                                    slot="suffix"
                                                    style="margin-right: 6px"
                                                >%</span>
                                            </el-input>
                                        </el-form-item>
                                        <span>邀请排名前</span>
                                        <el-form-item
                                            :prop="`pool_award_pool_step_set[${index}].award_money_percent`"
                                            :rules="rules.award_money_percent"
                                        >
                                            <el-input
                                                v-model="item.award_money_percent"
                                                size="medium"
                                                placeholder="请输入"
                                                style="width: 206px"
                                                :disabled="isDisabled"
                                            >
                                                <span
                                                    slot="suffix"
                                                    style="margin-right: 6px"
                                                >%</span>
                                            </el-input>
                                        </el-form-item>
                                        <span style="margin-left: 12px">的用户瓜分</span>
                                        <el-button
                                            type="text"
                                            size="medium"
                                            style="margin-left: 24px"
                                            :disabled="isDisabled"
                                            @click="ruleForm.pool_award_pool_step_set.splice(index, 1)"
                                        >
                                            删除
                                        </el-button>
                                    </template>
                                </div>
                                <el-button
                                    size="medium"
                                    icon="el-icon-plus"
                                    class="add-button"
                                    :disabled="isDisabled"
                                    @click="handleAdd"
                                >新增</el-button>
                            </div>
                        </el-form-item>
                    </el-form>
                </div>
                <!-- button -->
                <div class="footer">
                    <el-button
                        size="medium"
                        type="default"
                        @click="handleCancel()"
                    >
                        返回
                    </el-button>
                    <el-button
                        size="medium"
                        type="primary"
                        @click="handleSubmit()"
                    >
                        保存
                    </el-button>
                </div>
            </div>
        </div>
        <image-size-demo
            ref="imageSizeDemo"
            img-src="http://cdn.zsdx.cn/phaadmin/work-image-demo.png"
        />
    </div>
</template>

<script>
import {back} from '@/mixin/back';
import {deepClone, numberChinese} from "@/assets/js/utils";
import ImageUpload from "@/components/common/image-upload";
import ImageSizeDemo from "@/components/invite-friends/image-size-demo";
import {schoolSelectDialog} from "@/components/dialog/school-select";
const numberReg = /(?:^[1-9]([0-9]+)?(?:\.[0-9]{1,2})?$)|(?:^(?:0)$)|(?:^[0-9]\.[0-9](?:[0-9])?$)/;
const intReg = /^(0|[1-9][0-9]*|-[1-9][0-9]*)$/;

const award_step_model = {
    require_student_count: '',
    award_money: ''
};

const award_model = {
    rank_end_percent: '',
    award_money_percent: ''
};

const imageModel = {
    image: '',
};

export default {
    name: 'InvitePkActivityEdit',
    data() {
        const checkEndTime = (rule, value, callback) => {
            if(value > this.ruleForm.start_time) {
                callback();
            } else {
                callback(new Error('结束时间不能小于开始时间'));
            }
        };

        const checkStudentCount = (rule, value, callback) => {
            let result = this.ruleForm.pool_award_pool_step.filter(item => {
                return item.require_student_count == value;
            });

            if(result.length > 1) {
                callback(new Error('参与人数不能重复'));
            } else {
                callback();
            }
        };

        const checkPercent = (rule, value, callback) => {
            if(Number(value) > 0 && Number(value) <= 100) {
                callback();
            } else {
                callback(new Error('百分比输入不正确'));
            }
        };

        return {
            // add新增 edit编辑 detail查看
            type: 'add',
            status: '',
            ruleForm: {
                task_no: '',
                task_category: 104,
                status: 0,
                // 活动期数
                activity_index: undefined,
                start_time: '',
                end_time: '',
                // 活动图标
                task_logo_images: [deepClone(imageModel), deepClone(imageModel), deepClone(imageModel)],

                // 邀请奖励APP显示金额
                show_task_price: '',
                // 精英等级
                student_limit_stuagent_level: 1,
                // APP显示
                show_flag: 0,
                // 学校限制类型
                school_limit_type: 1,
                binding_school_ids: [],

                // 排名奖金
                rank_award: [],
                // 奖金池设置
                pool_award_pool_start_money: '',
                pool_award_pool_max_money: '',
                pool_award_pool_step_require_student_count: '',
                pool_award_pool_step_append_money: '',
                // 瓜分奖金池设置
                pool_award_pool_step_set: [{rank_end_percent: 100, award_money_percent: ''}],
                // 奖金池金额 v2.2.3 task_category 105
                pool_award_money: 0,
            },
            pageData: [],
            page: {
                now_page: 1,
                total_count: 0,
                page_size: 20
            },
            checkAllStatus: false,
            checkIndeterminate: false,
            multipleSelection: [],
            rules: {
                activity_index: [
                    {required: true, message: '请填写活动期数', trigger: 'blur'}
                ],
                start_time: [
                    {required: true, message: '请选择开始时间', trigger: 'change'}
                ],
                end_time: [
                    {required: true, message: '请选择结束时间', trigger: 'change'},
                    { validator: checkEndTime, trigger: 'change' }
                ],
                task_logo_images: [
                    {required: true, message: '请上传任务图片', trigger: 'change'}
                ],
                show_task_price: [
                    {required: true, message: '请填写邀请奖励APP显示金额', trigger: 'blur'},
                    {pattern: numberReg, message: '金额必须为数字', trigger: 'blur'},
                ],

                award_money: [
                    {required: true, message: '请填写奖励金额', trigger: 'blur'},
                    {pattern: numberReg, message: '金额必须为数字', trigger: 'blur'},
                ],
                require_student_count: [
                    {required: true, message: '请填写参与人数', trigger: 'blur'},
                    {pattern: /^(0|[1-9][0-9]*|-[1-9][0-9]*)$/, message: '人数必须为整数', trigger: 'blur'},
                    { validator: checkStudentCount, trigger: 'blur' }
                ],
                rank_end_percent: [
                    {required: true, message: '请填写排名百分比', trigger: 'blur'},
                    {pattern: numberReg, message: '百分比格式不正确', trigger: 'blur'},
                    {validator: checkPercent, trigger: 'blur'},
                ],
                award_money_percent: [
                    {required: true, message: '请填写奖池百分比', trigger: 'blur'},
                    {pattern: numberReg, message: '百分比格式不正确', trigger: 'blur'},
                    {validator: checkPercent, trigger: 'blur'},
                ],
                pool_award_pool_start_money: [
                    {required: true, message: '请填写奖金池基础金额', trigger: 'blur'},
                    {pattern: numberReg, message: '金额必须为数字', trigger: 'blur'},
                ],
                pool_award_pool_max_money: [
                    {required: true, message: '请填写奖金池上限', trigger: 'blur'},
                    {pattern: numberReg, message: '金额必须为数字', trigger: 'blur'},
                ],
                pool_award_pool_step_require_student_count: [
                    {required: true, message: '请填写下单人数', trigger: 'blur'},
                    {pattern: intReg, message: '人数格式不正确', trigger: 'blur'},
                ],
                pool_award_pool_step_append_money: [
                    {required: true, message: '请填写奖金池增加金额', trigger: 'blur'},
                    {pattern: numberReg, message: '金额必须为数字', trigger: 'blur'},
                ],
            },
            isDisabled: false,
            authResult: {}
        };
    },
    mixins: [back],
    watch: {},
    components: {ImageUpload, ImageSizeDemo},
    mounted() {
        this.init();
    },
    filters: {},
    methods: {
        numberChinese,
        /**
         * @description 页面初始化
         */
        init() {
            let query = this.$route.query;

            this.$store.commit('SET_HEADER', [{title: "APP后台"}, {title: '工作'}, {title: '邀请好友'}, {title: '邀请管理', path: '/student/invite-manage'},
                {title: '邀请PK赛', path: '/student/invite-pk-activity-list'},
                {title: query.type === 'edit' ? '编辑活动' : query.type === 'add' ? '新建活动' : '查看活动'}]);
            this.authResult = this.$route.meta.authResult;
            this.type = query.type;
            this.ruleForm.task_category = Number(query.task_category);
            // 编辑或查看时
            if (query.type !== 'add') {
                this.ruleForm.task_no = query.task_no;
                this.getDetail();
            }
            if (query.type === 'copy') {
                this.type = 'add';
                this.ruleForm.task_no = '';
            }
        },

        /**
         * 获取
         */
        getDetail() {
            let params = {
                task_no: this.ruleForm.task_no
            };

            this.$post('/student/task_stuagent_extra_student_invite_activity%5Cactivity%5Cget', params, resp => {
                if (resp.code === 1) {
                    let data = resp.data;
                    let query = this.$route.query;

                    data.re_apply_end_time = data.re_apply_end_time * 1000;
                    data.start_time = data.start_time * 1000;
                    data.end_time = data.end_time * 1000;
                    data.binding_school_ids.forEach(item => {
                        item.id = item.school_id;
                    });

                    this.ruleForm = data;
                    if(!this.ruleForm.task_logo_images || !this.ruleForm.task_logo_images.length) {
                        this.ruleForm.task_logo_images = [deepClone(imageModel), deepClone(imageModel), deepClone(imageModel)];
                    } else {
                        this.ruleForm.task_logo_images = this.ruleForm.task_logo_images.map(item => {
                            return {image: item};
                        });
                    }
                    if(query.type === 'copy') {
                        this.ruleForm.task_no = '';
                    }
                    this.getPageData();
                    this.isDisabled = this.ruleForm.status !== 0;
                } else {
                    this.$notify({
                        title: '提示',
                        message: resp.msg,
                        duration: 2000,
                        type: 'warning'
                    });
                }
            });
        },

        /**
         * @description 提交
         */
        handleSubmit() {
            this.$refs['ruleForm'].validate((valid) => {
                if (valid) {
                    let params = deepClone(this.ruleForm);
                    let rank_award = params.rank_award.map((item, index) => {
                        return {
                            rank: index + 1,
                            award_money: item.award_money
                        };
                    });
                    // 瓜分奖金池的百分比相加要等于100%
                    let sum = this.ruleForm.pool_award_pool_step_set.reduce((prev, cur) => {
                        return Number(cur.award_money_percent) + prev;
                    }, 0);

                    if(sum !== 100) {
                        this.$notify.warning({
                            title: '提示',
                            message: '瓜分奖金池的百分比之和不等于100%，保存失败'
                        });
                        return;
                    }

                    if(params.school_limit_type === 2 && params.binding_school_ids.length === 0) {
                        this.$notify({
                            title: '提示',
                            message: '请选择学校',
                            type: 'warning'
                        });
                        return;
                    }
                    params.binding_school_ids = params.binding_school_ids.map(item => {
                        return item.id;
                    }).join();

                    params.rank_award_json = JSON.stringify(rank_award);
                    params.pool_award_pool_step_set_json = JSON.stringify(params.pool_award_pool_step_set);
                    params.start_time = params.start_time / 1000;
                    params.end_time = params.end_time / 1000;
                    params.task_logo_images = params.task_logo_images.map(item => item.image).join();

                    delete params.rank_award;
                    delete params.pool_award_pool_step_set;
                    if(this.type === 'edit') params.task_no = this.$route.query.task_no;
                    this.$post('/student/task_stuagent_extra_student_invite_activity%5Cactivity%5Csave', params, resp => {
                        if (resp.code === 1) {
                            this.$notify({
                                title: '提示',
                                message: '保存成功',
                                duration: 2000,
                                type: 'success'
                            });
                            this.$router.push({
                                name: 'invitePkActivityList'
                            });
                        } else {
                            this.$notify({
                                title: '提示',
                                message: resp.msg,
                                duration: 2000,
                                type: 'warning'
                            });
                        }
                    });
                } else {
                    this.$nextTick(() => {
                        // 校验不通过
                        if(document.getElementsByClassName('el-form-item__error').length > 0){
                            this.$notify.warning({
                                title: '提示',
                                message: document.getElementsByClassName('el-form-item__error')[0].innerText
                            });
                        }
                        return false;
                    });
                }
            });
        },

        /**
         * @description 返回
         */
        handleCancel() {
            if (this.type === 'detail') {
                this.$router.push({
                    name: 'invitePkActivityList'
                });
            } else {
                this.$zdConfirm('离开此页面后，已填写的信息将不会保存，确认离开此页面吗？', '温馨提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$router.push({
                        name: 'invitePkActivityList'
                    });
                });
            }
        },

        /**
         * 路由跳转
         * @param routeName
         * @param query
         */
        handleRoute(routeName, query) {
            this.$router.push({
                name: routeName,
                query
            });
        },

        /**
         * 添加排名奖励
         */
        handleAddAward() {
            if(this.ruleForm.rank_award >= 10) {
                this.$message.warning('最多可设置10个');
                return;
            }
            this.ruleForm.rank_award.push({award_money: ''});
        },

        /**
         * 添加奖励瓜分设置
         */
        handleAdd() {
            this.ruleForm.pool_award_pool_step_set.push(deepClone(award_model));
        },

        /**
         * 选择学校
         * @returns {Promise<void>}
         */
        async handleSelectSchool(type = 'add') {
            let selectedData = type === 'add' ? [] : this.ruleForm.binding_school_ids;
            let result = await schoolSelectDialog({
                selectedData
            });

            if(result) {
                this.ruleForm.binding_school_ids = result;
                this.getPageData();
            }
        },

        /**
         * 处理学校分页数据
         */
        getPageData() {
            let data = this.getDataPagination(this.ruleForm.binding_school_ids, this.page.now_page, 5);

            this.pageData = data.list;
            this.page.now_page = data.currentPage;
            this.page.total_count = data.total;
            this.page.page_size = data.pageSize;
        },

        /**
         * @name  getDataPagination
         * @desc  前端分页方法
         * @param  {Number} currentPage 当前页码，默认1
         * @param  {Number} pageSize 每页最多显示条数，默认10
         * @param  {Array} totalData 总的数据集，默认为空数组
         * @return {Object} {
                list, //当前页展示数据，数组
                currentPage, //当前页码
                pageSize, //每页最多显示条数
                total, //总的数据条数
            }
         **/
        getDataPagination (totalData = [], currentPage = 1, pageSize = 10) {
            const { length } = totalData;
            const tableData = {
                list: [],
                currentPage,
                pageSize,
                total: length
            };

            if (pageSize >= length) {
                tableData.list = totalData;
                tableData.currentPage = 1;
            } else {
                const num = pageSize * (currentPage - 1);

                if (num < length) {
                    const startIndex = num;
                    const endIndex = num + pageSize - 1;

                    tableData.list = totalData.filter((_, index) => index >= startIndex && index <= endIndex);
                } else {
                    const size = parseInt(length / pageSize);
                    const rest = length % pageSize;

                    if (rest > 0) {
                        tableData.currentPage = size + 1;
                        tableData.list = totalData.filter((_, index) => index >= (pageSize * size) && index <= length);
                    } else if (rest === 0) {
                        tableData.currentPage = size;
                        tableData.list = totalData.filter((_, index) => index >= (pageSize * (size - 1)) && index <= length);
                    }
                }
            }
            return tableData;
        },

        /**
         * 移除学校
         * @param row
         */
        handleRemove(row) {
            let index = this.ruleForm.binding_school_ids.findIndex(item => {
                return item.id === row.id;
            });

            this.ruleForm.binding_school_ids.splice(index, 1);
            this.$refs.table.clearSelection();
            this.getPageData();
        },

        /**
         * 移除学校
         */
        handleRemoveBatch() {
            this.multipleSelection.forEach(item => {
                this.handleRemove(item);
            });
        },

        /**
         * 点击全选
         * @param val
         */
        handleSelectedAll(val) {
            if(val) {
                this.$refs.table.toggleAllSelection();
            } else {
                this.$refs.table.clearSelection();
            }
            this.checkIndeterminate = false;
        },

        /**
         * 选中状态变化
         * @param selection
         */
        handleSelectedChange(selection) {
            let checkedCount = selection.length;

            this.multipleSelection = selection;
            this.checkAllStatus = checkedCount === this.ruleForm.binding_school_ids.length;
            this.checkIndeterminate = checkedCount > 0 && checkedCount < this.ruleForm.binding_school_ids.length;
        },
    }
};
</script>

<style scoped lang="less">
.wrapper {
    width: 100%;

    .content-wrapper {
        display: flex;
        height: calc(100% - 24px);
        flex-direction: column;
        position: relative;
        margin: 12px;
        background: #fff;
        box-sizing: border-box;
        overflow-y: auto;
        &::-webkit-scrollbar {
            width: 4px;
        }
        .back {
            font-size: 14px;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: 500;
            color: #333333;
            cursor: pointer;
        }

        /deep/ .el-form {
            .is-required {
                .el-form-item__label {
                    &:before {
                        content: "*";
                        display: inline-block;
                        color: #F56C6C;
                    }
                }
            }
            .image-label {
                .el-form-item__label {
                    margin-top: 40px;
                }
            }
        }

        .form-view {
            background: #FBFBFB;
            border-radius: 2px;
            border: 1px solid #EEEEEE;
            margin: 24px 32px;
            box-sizing: border-box;
            padding: 32px;

            .form-tips {
                font-size: 12px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #999999;
                margin-left: 12px;
            }

            .radio-wrapper {
                margin-top: 12px;
                .radio-item {
                    margin-bottom: 24px;
                    display: flex;
                    line-height: 18px;
                    align-items: center;
                }
            }
            .task-logo-wrapper {
                /deep/ .pic-view {
                    display: flex;
                    align-items: flex-end;

                    .tips {
                        margin-bottom: 26px;
                    }
                }
            }

            .form-title {
                font-size: 16px;
                font-family: PingFangSC-Semibold, PingFang SC;
                font-weight: 600;
                color: #333333;
                padding-bottom: 12px;
                border-bottom: 1px solid #E9E9E9;
                margin-bottom: 24px;
                margin-top: 60px;
            }
        }
        .upload-list {
            display: flex;
            align-items: center;
            .upload-item {
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                .upload-text {
                    color: #999;
                    text-align: center;
                    margin-right: 16px;
                }
            }
        }

        .rank-wrapper {
            background: #F7F7F7;
            border-radius: 4px;
            border: 1px solid #EEEEEE;
            padding: 24px;
            .rank-list {
                display: flex;
                flex-wrap: wrap;
                margin: -24px 0 0 -24px;
                .rank-item {
                    width: 30.8%;
                    margin: 24px 0 0 24px;
                    &__header {
                        font-size: 14px;
                        font-family: PingFangSC-Regular, PingFang SC;
                        font-weight: 400;
                        color: #333333;
                        margin-bottom: 10px;
                        display: flex;
                        align-items: center;
                        justify-content: space-between;
                        line-height: 14px;
                        .el-button {
                            padding: 0;
                        }
                    }
                }
            }
            .empty-text {
                font-size: 14px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #999999;
                line-height: 14px;
            }
            .add-button {
                width: 120px;
                height: 36px;
                border-radius: 4px;
                border: 1px solid #20A0FF;
                font-size: 14px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #20A0FF;
                background: #fff;
                margin-top: 24px;
            }
        }
        .school-wrapper {
            width: 598px;
            background: #FFFFFF;
            border-radius: 4px;
            border: 1px solid #EEEEEE;
            .school-header {
                height: 54px;
                background: #FFFFFF;
                border-radius: 4px 4px 0 0;
                border-bottom: 1px solid #EEEEEE;
                font-size: 14px;
                font-family: PingFangSC-Medium, PingFang SC;
                font-weight: 500;
                color: #333333;
                padding: 0 35px;
                display: flex;
                align-items: center;
            }
            .school-content {
                padding: 24px 0 0;
                .btn-view {
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    margin-bottom: 16px;
                    padding: 0 24px;
                    .count {
                        color: #F53341;
                    }
                }
                .table-wrapper {
                    padding: 0 24px;
                }
                .table-footer {
                    height: 50px;
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    padding: 0 24px 0 42px;
                    font-size: 14px;
                    font-family: PingFangSC-Regular, PingFang SC;
                    font-weight: 400;
                    color: #333333;
                    border-top: 1px solid #EBEEF5;
                    .count {
                        color: #F53341;
                    }
                    .pagination {
                        margin-top: 12px;
                    }
                }
            }
            .school-content-empty {
                height: 272px;
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                line-height: normal;
                .empty-title {
                    font-size: 14px;
                    font-family: PingFangSC-Medium, PingFang SC;
                    font-weight: 500;
                    color: #333333;
                    margin-bottom: 16px;
                }
                .empty-sub-title {
                    font-size: 12px;
                    font-family: PingFangSC-Regular, PingFang SC;
                    font-weight: 400;
                    color: #333333;
                    margin-bottom: 20px;
                }
                .empty-btn {
                    width: 130px;
                    height: 36px;
                    background: rgba(255, 255, 255, 0);
                    border-radius: 4px;
                    border: 1px solid #1890FF;
                    font-size: 14px;
                    font-family: PingFangSC-Regular, PingFang SC;
                    font-weight: 400;
                    color: #1890FF;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    cursor: pointer;
                }
            }
        }
        .award-wrapper {
            background: #F7F7F7;
            border-radius: 4px;
            border: 1px solid #EEEEEE;
            padding: 24px 24px 2px;
            .award-item {
                display: flex;
                align-items: center;
                font-size: 14px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #333333;
                margin-bottom: 24px;
                span {
                    margin-right: 10px;
                }
                .delete {
                    margin-left: 24px;
                    cursor: pointer;
                    font-size: 14px;
                    font-family: PingFangSC-Regular, PingFang SC;
                    font-weight: 400;
                    color: #666666;
                    user-select: none;
                }
            }
            .add-button {
                width: 120px;
                height: 36px;
                border-radius: 4px;
                border: 1px solid #20A0FF;
                font-size: 14px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #20A0FF;
                background: #fff;
            }
        }
        /*footer*/
        .footer {
            box-sizing: border-box;
            padding-left: 176px;
            margin-top: 8px;
            margin-bottom: 52px;

            .el-button {
                width: 120px;
                margin: 0 16px 12px;
            }
        }
    }

    /deep/ .el-dialog__header {
        padding-top: 10px;
        box-shadow: 0px 1px 0px 0px rgba(233, 233, 233, 1);
        display: flex;
        align-items: center;
        background: #FAFAFA;
        border-radius: 4px 4px 0 0;

        .el-dialog__title {
            font-weight: 500;
            color: #333;
            font-size: 14px;
        }

        .el-icon-close:before {
            color: rgb(194, 194, 194);
            font-size: 17px;
            font-weight: bold;
        }

        .el-dialog__headerbtn {
            top: 14px;
        }
    }

    /deep/ .el-textarea__inner {
        resize: none;
    }

    /deep/.edui-default {
        .edui-editor {
            width: 862px!important;
        }
    }
    /deep/ .el-input-number .el-input__inner {
        text-align: left;
    }

    /deep/ .pic-view {
        display: flex;
        align-items: flex-end;

        .tips {
            margin-bottom: 40px;
        }
        .pic-item {
            margin-bottom: 0!important;
        }
        .uploader-customer {
            background: #fff!important;
        }
    }
}

/deep/ .el-table {
    &::before {
        height: 0;
    }
    .el-table__row {
        &:last-of-type {
            td {
                border: none;
            }
        }
    }
    th {
        background: #f2f2f2!important;
        font-size: 14px!important;
        font-family: PingFangSC-Medium, PingFang SC!important;
        font-weight: 500!important;
        color: #333333!important;
        height: 44px!important;
        padding: 0!important;
    }
}
</style>

